package com.github.binarywang.demo.wechat.controller;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by DELL on 2018/2/27.
 */
@Controller
public class PageController {


    @Autowired
    private WxMpService wxService;


    @RequestMapping(value = "/home",method = RequestMethod.GET)
    public String index(HttpServletRequest req, Model model) {

            WxMpUser user =  (WxMpUser) req.getSession().getAttribute("WeixinUserInfo");

            String url="";

            if(user==null){
                url = wxService.oauth2buildAuthorizationUrl("http://antball.free.ngrok.cc/index/","snsapi_userinfo","");
            }else{
                url = "http://antball.free.ngrok.cc/index/";
            }

        return "redirect:"+url;


    }



    //这里指定是条状的jsp界面
    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public String index(@RequestParam(value = "code",required = false) String code,HttpServletRequest req, Model model) {
        if(StringUtils.isNotEmpty(code)){
            try {
                WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxService.oauth2getAccessToken(code);
                WxMpUser wxMpUser = wxService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);

                req.getSession().setAttribute("WeixinUserInfo", wxMpUser);
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }


        WxMpUser user =  (WxMpUser) req.getSession().getAttribute("WeixinUserInfo");

        model.addAttribute("openid", user.getOpenId());
        model.addAttribute("nickname", user.getNickname());


        model.addAttribute("name", "this is my fries测试不是好领导了副经理看fjldj 1123123");
        return "inde";
    }
}
